// 工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 使用 ESM 模块
const esm = require("esm");
const requireModule = esm(module);

// 读取模块
const { readAllValues } = requireModule(
  "../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("./utils/checkAccuracy.js");

// 读取历史数据
const allValues = readAllValues("m")
// .slice(0, 500);

// 所有号码
const allNumbers = Array.from({ length: 49 }, (_, i) => i + 1).map((n) =>
  n < 10 ? `0${n}` : `${n}`
);

// 是否使用滑动窗口
const useWindow = true;

// 保存每个 windowSize 对应的统计结果
const windowStats = [];

// 封装预测逻辑为函数
function runPrediction(windowSize) {
  const predictResults = [];

  allValues.forEach((item, index) => {
    const temp = useWindow
      ? allValues.slice(Math.max(0, index - windowSize), index)
      : allValues.slice(0, index);

    if (!temp.length) return;

    const stats = {};
    allNumbers.forEach((num) => {
      stats[num] = {
        appearCount: 0,
        lastAppearDistance: Infinity,
      };
    });

    temp.forEach((entry, i) => {
      const number = entry.number;
      if (stats[number]) {
        stats[number].appearCount++;
        stats[number].lastAppearDistance = temp.length - i;
      }
    });

    const scoreMap = {};
    for (const num of allNumbers) {
      const { appearCount, lastAppearDistance } = stats[num];
      const score =
        appearCount * 2 + Math.min(lastAppearDistance, 10);
      scoreMap[num] = score;
    }

    const finalSelected = Object.entries(scoreMap)
      .sort((a, b) => b[1] - a[1])
      .map(([num]) => num)
      .slice(0, 32);

    predictResults.push(checkAccuracy(finalSelected, item.number));
  });

  // 统计结果
  const total = predictResults.length;
  const correct = predictResults.filter((x) => x === 1).length;
  const accuracy = total > 0 ? (correct / total * 100).toFixed(2) : 0;

  let maxWrongStreak = 0;
  let currentStreak = 0;
  predictResults.forEach((res) => {
    if (res === 0) {
      currentStreak++;
      if (currentStreak > maxWrongStreak) {
        maxWrongStreak = currentStreak;
      }
    } else {
      currentStreak = 0;
    }
  });

  return {
    windowSize,
    accuracy: Number(accuracy),
    correct,
    total,
    maxWrongStreak,
  };
}

// 尝试 windowSize 从 30 到 300
for (let size = 30; size <= 300; size++) {
  const result = runPrediction(size);
  windowStats.push(result);
}

// 找出最高准确率的窗口大小
const best = _.maxBy(windowStats, "accuracy");

// 输出所有统计结果（可选）
// console.table(windowStats);

// 输出最佳窗口信息
console.log("✅ 最佳窗口大小结果：");
console.log(`Window Size: ${best.windowSize}`);
console.log(`准确率: ${best.accuracy}%`);
console.log(`命中次数: ${best.correct}/${best.total}`);
console.log(`最大连续错误次数: ${best.maxWrongStreak}`);
